//
//  MTInfoVerificationPickerCell.swift
//  MT
//
//  Created by M on 2020/1/4.
//  Copyright © 2020 张强. All rights reserved.
//

import UIKit
import MTCategory

class MTInfoVerificationPickerCell: BaseMTInfoVerificationCell {
    
    /// 代理
    weak var delegate: MTInfoVerificationInputCellDelegate?
    
    /// 所有省份
//    private var provinces: [ProvinceModel]?
    /// 选择器数据源
    private var pickerViewSource: [Any]?
    /// 选择器下标
    private var i1: Int = 0
    private var i2: Int = 0
    private var i3: Int = 0
    /// 类型
    override var type: UserProfileInfos? {
        didSet {
            guard let type = type else { return }
            setPickerView(withType: type)
        }
    }
    /// 内容
    var content: String? {
        didSet {
            textField.text = content
        }
    }
    
    /// 选择器
    lazy var pickerView: UIPickerView = {
        let pickerView = UIPickerView()
        pickerView.backgroundColor = UIColor.white
        pickerView.delegate = self
        pickerView.dataSource = self
        return pickerView
    }()
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        setup()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
}

// MARK: ------------------ Overrides ----------------------
extension MTInfoVerificationPickerCell {
    
    override func prepareForReuse() {
        super.prepareForReuse()
        titleLabel.textColor = UIColor(hex:0x1d1a1a)
        titleLabel.font = PingFangSCSemiboldFont(14)
        underline.backgroundColor = UIColor(hex: 0xe7e7e7)
    }
    
}

// MARK: ------------------ 初始化 ----------------------
extension MTInfoVerificationPickerCell {
    
    private func setup() {
        textField.tintColor = .white
        textField.delegate = self
        textField.textColor = UIColor(hex:0x1d1a1a)
        textField.font = PingFangSCMediumFont(14)
//        textField.setValue(PingFangSCMediumFont(14), forKeyPath: "_placeholderLabel.font")
        textField.addTarget(self, action: #selector(inputCell(textFieldAllEditingEvents:)), for: .allEditingEvents)
    }
    
}

// MARK: ------------------ 事件方法 ----------------------
@objc
extension MTInfoVerificationPickerCell {
    
    /// 文字输入方法
    private func inputCell(textFieldAllEditingEvents sender: UITextField) {
        if let c = sender.text?.utf8.count, let type = type, type == .nickname, c > type.maximumTextCount ?? 0 {
            titleLabel.textColor = UIColor(hex: 0x1d1a1a)
            underline.backgroundColor = UIColor(hex: 0xe7e7e7)
        } else {
            titleLabel.textColor = UIColor(hex: 0x1d1a1a)
            underline.backgroundColor = UIColor(hex: 0xe7e7e7)
        }

        switch type {
        case .location:
            if let source = pickerViewSource as? [ProvinceModel] {
                let province = source[i1].province
                let city = source[i1].cities?[i2].name
                let area = source[i1].cities?[i2].areas?[i3]
                textField.text = "\(province ?? "")-\(city ?? "")-\(area ?? "")"
            }
            break
        case .birthday:
            if sender.text?.count == 0 {
                let fmt = DateFormatter()
                fmt.dateFormat = "yyyy-MM-dd"
                let dateString = fmt.string(from: Date())
                textField.text = dateString
            }
            break
        default:
            break
        }
        
        if let delegate = delegate, let type = type {
            delegate.inputCell?(self, infoType: type, didInputText: sender.text)
        }
    }
    
    /// 日期选择
    private func datePicker(didChanged picker: UIDatePicker) {
        let fmt = DateFormatter()
        fmt.dateFormat = "yyyy-MM-dd"
        let dateString = fmt.string(from: picker.date)
        textField.text = dateString
        if let delegate = delegate, let type = type {
            delegate.inputCell?(self, infoType: type, didInputText: dateString)
        }
    }
    
    /// 点击完成
    private func pickerView(didClickDoneBarButtonItem sender: UIBarButtonItem) {
        textField.resignFirstResponder()
    }
    
}

// MARK: ------------------------------------ 设置 PickerView ----------------------------------------
extension MTInfoVerificationPickerCell {
    
    private func setPickerView(withType type: UserProfileInfos) {
        switch type {
            /// 生日选择
        case .birthday:
            setDatePicker()
            break

            /// 城市选择
        case .location:
            guard let plistPath = type.pickerPlistName, let array = NSArray(contentsOfFile: plistPath) as? [[String:Any]] else { return }
            var provinces: [ProvinceModel] = []
            for a in array {
                let p = ProvinceModel(dict: a)
                provinces.append(p)
            }
            self.pickerViewSource = provinces
            let province = provinces[0].province
            let city = provinces[0].cities?[0].name
            let area = provinces[0].cities?[0].areas?[0]
            self.textField.text = "\(province ?? "")-\(city ?? "")-\(area ?? "")"
            self.textField.inputView = self.pickerView
            pickerView.reloadAllComponents()
            break
            
        case .body_height, .body_weight, .constellation, .degree:
            if let source = type.pickerSources {
                self.pickerViewSource = source
            }
            self.textField.inputView = self.pickerView
            pickerView.reloadAllComponents()
            break
            
        default: break
        }
    }
    
    private func setDatePicker() {
        let datePicker = UIDatePicker()
        datePicker.locale = Locale(identifier: "zh")
        datePicker.datePickerMode = .date
        datePicker.minimumDate = Date(timeIntervalSince1970: -365 * 40 * 24 * 3600)
        datePicker.maximumDate = Date()
        datePicker.backgroundColor = UIColor.theme.background
        datePicker.addTarget(self, action: #selector(datePicker(didChanged:)), for: .valueChanged)
        textField.inputView = datePicker
    }
    
}

// MARK: ------------------ 所有代理 ----------------------
// MARK: ------------------ UITextFieldDelegate ----------------------
extension MTInfoVerificationPickerCell: UITextFieldDelegate {
    
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        if let type = self.type, (type == .birthday || type == .location) {
            return false
        }
        return true
    }
    
}

// MARK: ------------------ UIPickerViewDelegate ----------------------
extension MTInfoVerificationPickerCell: UIPickerViewDelegate {
    
    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
        guard let type = type else { return }
        var name: String = ""
        
        switch type {
            
            /// 城市
        case .location:
            if component == 0 {
                i1 = row
                i2 = 0
                i3 = 0
                pickerView.reloadComponent(1)
                pickerView.reloadComponent(2)
            } else if component == 1 {
                i2 = row
                i3 = 0
                pickerView.reloadComponent(2)
            } else {
                i3 = row
            }
            if let source = pickerViewSource as? [ProvinceModel] {
                let province = source[i1].province
                let city = source[i1].cities?[i2].name
                let area = source[i1].cities?[i2].areas?[i3]
                if let province = province {
                    name += province + "-"
                }
                if let city = city {
                    name += city + "-"
                }
                if let area = area {
                    name += area
                }
            }
            break
            
        case .body_height, .body_weight, .constellation, .degree:
            if let source = pickerViewSource as? [String] {
                name = source[row]
                
            }
            break
            
        default:
            break
        }
        
        textField.text = name
        if let delegate = delegate {
            delegate.inputCell?(self, infoType: type, didInputText: name)
        }
    }
    
}

// MARK: ------------------ UIPickerViewDataSource ----------------------
extension MTInfoVerificationPickerCell: UIPickerViewDataSource {
 
    func numberOfComponents(in pickerView: UIPickerView) -> Int {
        guard let type = type else { return 0 }
        switch type {
        case .location:
            return 3
        case .body_height, .body_weight, .constellation, .degree:
            return 1
        default:
            return 0
        }
    }
    
    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        guard let type = type else { return 0 }
        switch type {
        case .location:
            if let source = pickerViewSource as? [ProvinceModel] {
                if component == 0 {
                    return source.count
                } else if component == 1 {
                    return source[i1].cities?.count ?? 0
                } else {
                    return source[i1].cities?[i2].areas?.count ?? 0
                }
            }
            return 0
        case .body_height, .body_weight, .constellation, .degree:
            if let source = pickerViewSource as? [String] {
                return source.count
            }
            return 0
        default:
            return 0
        }
    }
    
    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
        guard let type = type else { return nil }
        switch type {
        case .location:
            if let source = pickerViewSource as? [ProvinceModel] {
                if component == 0 {
                    return source[row].province ?? ""
                } else if component == 1 {
                    return source[i1].cities?[row].name ?? ""
                } else {
                    return source[i1].cities?[i2].areas?[row] ?? ""
                }
            }
            return nil
        case .body_height, .body_weight, .constellation, .degree:
            if let source = pickerViewSource as? [String] {
                textField.text = source[row]
                return source[row]
            }
            return nil
        default:
            return nil
        }
    }
    
    func pickerView(_ pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusing view: UIView?) -> UIView {
        var pickerLabel = view as? UILabel
        if pickerLabel == nil {
            pickerLabel = UILabel()
            pickerLabel?.textColor = UIColor.text.x1d1a1a
            pickerLabel?.font = PingFangSCSemiboldFont(16)
            pickerLabel?.textAlignment = .center
            pickerLabel?.backgroundColor = .white
        }
        pickerLabel?.text = self.pickerView(pickerView, titleForRow: row, forComponent: component)
        return pickerLabel!
    }
    
}
